<?php
/**
* @file $Id: Administration.php 580 2007-06-05 19:19:11Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/


if ($_REQUEST['month_date'] 
&& $_REQUEST['day_date'] 
&& $_REQUEST['year_date']
) {
	while(!VerifyDate($date = $_REQUEST['day_date'].'-'.$_REQUEST['month_date'].'-'.$_REQUEST['year_date'])) {
		$_REQUEST['day_date']--;
	}
	
	if ($_SESSION['Administration.php']['date'] 
	&& $_SESSION['Administration.php']['date'] != $date
	) {
		unset($_REQUEST['attendance']);
		unset($_REQUEST['attendance_day']);
	}
}
else {
	$date = DBDate();
	$_REQUEST['day_date'] = date('d');
	$_REQUEST['month_date'] = strtoupper(date('M'));
	$_REQUEST['year_date'] = date('y');
}

$day = DayNameToLetter(date('D', 
		mktime(0, 0, 0, (MonthNWSwitch($_REQUEST['month_date'], 'tonum') * 1),
		($_REQUEST['day_date']*1), $_REQUEST['year_date'])));
$user_syear = UserSyear();
$user_school = UserSchool();
$current_mp = GetCurrentMP('QTR',$date);
$mp_list = GetAllMP('QTR', $current_mp);

if (!$_REQUEST['table']) {
	$_REQUEST['table'] = '0';
}

if ($_REQUEST['table'] == 0) {
	$table = 'ATTENDANCE_PERIOD';
	$table_name_constraint = '';
}
else {
	$table = 'LUNCH_PERIOD';
	$table_name_constraint = " AND         TABLE_NAME='$_REQUEST[table]'";
}

$_SESSION['Administration.php']['date'] = $date;

$current_RET = DBGet(DBQuery("
		SELECT       ATTENDANCE_TEACHER_CODE
		 ,           ATTENDANCE_CODE
		 ,           ATTENDANCE_REASON
		 ,           STUDENT_ID
		 ,           ADMIN
		 ,           PERIOD_ID
		 ,           COURSE_PERIOD_ID
		FROM         $table
		WHERE        SCHOOL_DATE = '$date' 
		".$table_name_constraint
		), array(), array('STUDENT_ID', 'PERIOD_ID'));

if ($_REQUEST['attendance'] 
&& $_POST['attendance'] 
&& AllowEdit()
) {
	foreach ($_REQUEST['attendance'] as $student_id => $values) {
		foreach ($values as $period_id => $columns) {
			if ($current_RET[$student_id][$period_id]) {
				$sql = "
						UPDATE       $table 
						SET          ADMIN = 'Y'";
				
				foreach ($columns as $column => $value) {
					$sql .= "
						 ,           $column = '".str_replace("\'","''",$value)."'";
				}

				$sql .= "
						WHERE        SCHOOL_DATE = '$date'
						 AND         PERIOD_ID = '$period_id'
						 AND         STUDENT_ID = '$student_id'
						".$table_name_constraint;
				DBQuery($sql);
			}
			else {
				$cp_id = $current_RET[$student_id]['COURSE_PERIOD_ID'];

//				$period_id = DBGet(DBQuery("
//						SELECT       PERIOD_ID 
//						FROM         COURSE_PERIODS 
//						WHERE        COURSE_PERIOD_ID = '$period'
//						"));
						
//				$period_id = $period_id[1]['PERIOD_ID'];

//				$sql = 		'INSERT INTO '.$table;  - this is done a bit lower now -BL
				$fields = 	' STUDENT_ID
							, SCHOOL_DATE
							, PERIOD_ID
							, MARKING_PERIOD_ID
							, COURSE_PERIOD_ID
							, ADMIN
							';
				$values = 	" '$student_id'
							, '$date'
							, '$period_id'
							, '$current_mp'
							, '$cp_id'
							, 'Y'
							";

				if ($table == 'LUNCH_PERIOD') {
					$fields .= ', TABLE_NAME';
					$values .= ", '$_REQUEST[table]'";
				}
				
				$go = 0;
				foreach ($columns as $column => $value) {
					if ($value) {
						$fields .= ", $column";
						$values .= ", '".str_replace("\'", "''", $value)."'";
						$go = true;
					}
				}
				
				if ($go) {
					DBQuery("
							INSERT INTO $table ( $fields ) 
							values ( $values )
							");
				}
			}
		}
		
		UpdateAttendanceDaily($student_id
				,$date
				,$_REQUEST['attendance_day'][$student_id]['COMMENT']
					? $_REQUEST['attendance_day'][$student_id]['COMMENT']
					: false
				);
				
		unset($_REQUEST['attendance_day'][$student_id]);
	}
	
	$current_RET = DBGet(DBQuery("
			SELECT       ATTENDANCE_TEACHER_CODE
			 ,           ATTENDANCE_CODE
			 ,           ATTENDANCE_REASON
			 ,           STUDENT_ID
			 ,           ADMIN
			 ,           PERIOD_ID
			 ,           COURSE_PERIOD_ID 
			FROM         $table 
			WHERE        SCHOOL_DATE = '$date'
			".$table_name_constraint
			), array(), array('STUDENT_ID', 'PERIOD_ID'));
			 
	unset($_REQUEST['attendance']);
	unset($_SESSION['_REQUEST_vars']['attendance']);
	unset($_SESSION['_REQUEST_vars']['attendance_day']);
}

if (count($_REQUEST['attendance_day'])) {
	foreach ($_REQUEST['attendance_day'] as $student_id => $comment) {
		UpdateAttendanceDaily($student_id, $date, $comment['COMMENT']);
	}
	unset($_REQUEST['attendance_day']);
}

$codes_RET = DBGet(DBQuery("
		SELECT       ID
		 ,           SHORT_NAME
		 ,           TITLE 
		FROM         ATTENDANCE_CODES 
		WHERE        SCHOOL_ID = '$user_school'
		 AND         SYEAR = '$user_syear' 
		 AND         TABLE_NAME = '$_REQUEST[table]' 
		ORDER BY     SORT_ORDER
		 ,           SHORT_NAME
		"));
		
$periods_RET = DBGet(DBQuery("
		SELECT       PERIOD_ID
		 ,           SHORT_NAME
		 ,           TITLE 
		FROM         SCHOOL_PERIODS 
		WHERE        SCHOOL_ID = '$user_school' 
		 AND         SYEAR = '$user_syear' 
		 AND         ATTENDANCE = 'Y' 
		ORDER BY     SORT_ORDER
		"));

if (isset($_REQUEST['student_id']) 
&& $_REQUEST['student_id'] != 'new'
) {
	if (UserStudentID() != $_REQUEST['student_id']) {
		$_SESSION['student_id'] = $_REQUEST['student_id'];
		echo '
			<script language="JavaScript">
				parent.side.location="'.$_SESSION['Side_PHP_SELF']
				.'?modcat=" + parent.side.document.forms[0].modcat.value;
			</script>';
	}
	
	$functions = array('ATTENDANCE_CODE' => '_makeCodePulldown'
			, 'ATTENDANCE_TEACHER_CODE'  => '_makeCode'
			, 'ATTENDANCE_REASON'        => '_makeReasonInput'
			);
			
	$schedule_RET = DBGet(DBQuery("
			SELECT       s.STUDENT_ID
			 ,           c.TITLE || ' - ' || s.COURSE_WEIGHT AS COURSE
			 ,           cp.PERIOD_ID
			 ,           cp.COURSE_PERIOD_ID
			 ,           cp.TITLE AS PERIOD_TITLE
			 ,           '' AS ATTENDANCE_CODE
			 ,           '' AS ATTENDANCE_TEACHER_CODE
			 ,           '' AS ATTENDANCE_REASON
			 ,           cp.DAYS
			FROM         SCHEDULE s
			 JOIN        COURSES c
			  ON         c.COURSE_ID = s.COURSE_ID 
			 JOIN        COURSE_PERIODS cp
			  ON         cp.COURSE_PERIOD_ID = s.COURSE_PERIOD_ID 
			 JOIN        SCHOOL_PERIODS p 
			  ON         p.PERIOD_ID = cp.PERIOD_ID 
			WHERE        s.SYEAR = '$user_syear' 
			 AND         s.SCHOOL_ID = '$user_school' 
			 AND         s.MARKING_PERIOD_ID IN ($mp_list)
			 AND         cp.DOES_ATTENDANCE = 'Y'
			 AND         s.STUDENT_ID = '$_REQUEST[student_id]' 
			 AND         '$date' >= s.START_DATE 
			 AND         ('$date' <= s.END_DATE OR s.END_DATE IS NULL)
			ORDER BY     p.SORT_ORDER
			"), $functions);
			 
	$columns = array('PERIOD_TITLE'     => 'Period - Teacher'
			, 'COURSE'                  => 'Course'
			, 'ATTENDANCE_CODE'         => 'Attendance Code'
			, 'ATTENDANCE_TEACHER_CODE' => 'Teacher\'s Entry'
			, 'ATTENDANCE_REASON'       => 'Comments'
			);
			
	echo '
		<form action="'
			.'Modules.php'
			.'?modname=' . $_REQUEST[modname]
			.'&modfunc=student'
			.'&student_id.=' . $_REQUEST[student_id] . '"
			method="POST">
			';
			
	DrawHeader(ProgramTitle()
			, SubmitButton(_('Update'))
			);
			
	DrawHeader(' &nbsp; &nbsp; <b>'._('Report Date').': </b>'
			.PrepareDate($date, '_date', false, array('submit' => true))
			);
			
	ListOutput($schedule_RET, $columns, _('Course'), _('Courses'));
	
	echo '
		</form>';
}
else {
	$extra['WHERE'] = "
			AND EXISTS (
					SELECT       '' 
					FROM         $table ap
					 JOIN        ATTENDANCE_CODES ac 
					  ON         ap.ATTENDANCE_CODE = ac.ID 
					WHERE        ap.SCHOOL_DATE = '$date' 
					 AND         ap.STUDENT_ID = ssm.STUDENT_ID 
					 AND         ac.SCHOOL_ID = ssm.SCHOOL_ID 
					 AND         ac.SYEAR = ssm.SYEAR 
					".str_replace('TABLE_NAME','ac.TABLE_NAME',$table_name_constraint);
	
	if (count($_REQUEST['codes'])) {
		$REQ_codes = $_REQUEST['codes'];
		foreach ($REQ_codes as $key => $value) {
			if (!$value) {
				unset($REQ_codes[$key]);
			}
			elseif ($value == 'A') {
				$abs = true;
			}
		}
	}
	else {
		$abs = true;
	}
	
	if (count($REQ_codes) && !$abs) {
		$extra['WHERE'] .= "
					 AND         ac.ID IN (";
		foreach ($REQ_codes as $code) {
			$extra['WHERE'] .= "'".$code."',";
		}
		$extra['WHERE'] = substr($extra['WHERE'], 0, -1).')';
	}
	elseif ($abs) {
		$RET = DBGet(DBQuery("
				SELECT       ID 
				FROM         ATTENDANCE_CODES 
				WHERE        SYEAR = '$user_syear' 
				 AND         SCHOOL_ID = '$user_school' 
				 AND         (DEFAULT_CODE != 'Y' OR DEFAULT_CODE IS NULL) 
				 AND         TABLE_NAME = '$_REQUEST[table]'
				"));
				
		if (count($RET)) {
			$extra['WHERE'] .= "AND ac.ID IN (";
			foreach ($RET as $code) {
				$extra['WHERE'] .= "'".$code['ID']."',";
			}
			$extra['WHERE'] = substr($extra['WHERE'], 0, -1).')';
		}
	}
	$extra['WHERE'] .= ')';
	
	// EXPANDED VIEW BREAKS THIS QUERY.  PLUS, PHONE IS ALREADY AN OPTION IN EXPANDED VIEW
	if ($_REQUEST['expanded_view'] != 'true' 
	&& $_REQUEST['_FOCUS_PDF'] != 'true'
	) {
		$extra2['WHERE'] = $extra['WHERE'];
		$extra2['SELECT_ONLY'] = '
				             ssm.STUDENT_ID
				 ,           p.PERSON_ID
				 ,           p.FIRST_NAME
				 ,           p.LAST_NAME
				 ,           sjp.STUDENT_RELATION
				 ,           pjc.TITLE
				 ,           pjc.VALUE
				 ,           a.PHONE
				 ,           sjp.ADDRESS_ID 
				 ';
		$extra2['FROM'] .= "
				 ,           ADDRESS a
				 ,           STUDENTS_JOIN_ADDRESS sja 
				 LEFT JOIN   STUDENTS_JOIN_PEOPLE sjp 
				  ON         sja.STUDENT_ID = sjp.STUDENT_ID 
				   AND       sja.ADDRESS_ID = sjp.ADDRESS_ID 
				   AND (     sjp.CUSTODY = 'Y' 
				    OR       sjp.EMERGENCY = 'Y' )
				 LEFT JOIN   PEOPLE p 
				  ON         p.PERSON_ID = sjp.PERSON_ID 
				 LEFT JOIN   PEOPLE_JOIN_CONTACTS pjc 
				  ON         pjc.PERSON_ID = p.PERSON_ID 
				";
		$extra2['WHERE'] .= ' 
				 AND         a.ADDRESS_ID = sja.ADDRESS_ID 
				 AND         sja.STUDENT_ID = ssm.STUDENT_ID 
				';
		
		if ($extra2['ORDER_BY']) {
			$extra2['ORDER_BY'] .= ',';
		}
		
		$extra2['ORDER_BY'] .= " COALESCE(sjp.CUSTODY, 'N') DESC";
		$extra2['group'] = array('STUDENT_ID', 'PERSON_ID');
		$contacts_RET = GetStuList($extra2);
		$extra['columns_before']['PHONE'] = '
				<img src="assets/down_phone_button.gif" 
					border="0" 
					width="20" 
				/>';
		$extra['columns_before']['PHOTO'] = '
				<img src="assets/camera.gif" 
					border="0" 
					width="20" 
				/>';
	}
	
	$columns = array();
	$extra['SELECT'] .= "
			,           NULL AS STATE_VALUE
			,           NULL AS DAILY_COMMENT
			,           NULL AS PHONE
			,           NULL AS PHOTO";
	$extra['functions']['PHONE'] = '_makePhone';
	$extra['functions']['PHOTO'] = '_makePhoto';
	$extra['functions']['STATE_VALUE'] = '_makeStateValue';
	$extra['functions']['DAILY_COMMENT'] = '_makeStateValue';

	if ($_REQUEST['table'] == '0' 
	|| !$_REQUEST['table']
	) {
		$extra['columns_after']['STATE_VALUE'] = 'Present';
	}
	
	$extra['columns_after']['DAILY_COMMENT'] = 'Comment';
	$extra['link']['FULL_NAME']['link'] = 
			'Modules.php'
			.'?modname='.$_REQUEST['modname']
			.'&month_date='.$_REQUEST['month_date']
			.'&day_date='.$_REQUEST['day_date']
			.'&year_date='.$_REQUEST['year_date'];
	$extra['link']['FULL_NAME']['variables'] = array('student_id' => 'STUDENT_ID');
	$extra['BackPrompt'] = false;
	$extra['Redirect'] = false;
	$extra['new'] = true;
	
	foreach ($periods_RET as $period) {
		$extra['SELECT'] .= ",'' AS PERIOD_".$period['PERIOD_ID'];
		$extra['functions']['PERIOD_'.$period['PERIOD_ID']] = '_makeCodePulldown';
		$extra['columns_after']['PERIOD_'.$period['PERIOD_ID']] = $period['SHORT_NAME'];
	}

	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['day_date']);
	unset($tmp_REQUEST['month_date']);
	unset($tmp_REQUEST['year_date']);
	unset($tmp_REQUEST['codes']);
	$action = PreparePHP_SELF($tmp_REQUEST);
	echo '<form action="'.$action.'" method="POST">';
	DrawHeader(ProgramTitle(), SubmitButton(_('Update')));
	
	if ($REQ_codes)	{
		foreach ($REQ_codes as $code) {
			$code_pulldowns .= _makeCodeSearch($code);
		}
	}
	elseif ($abs) {
		$code_pulldowns = _makeCodeSearch('A');
	}
	else {
		$code_pulldowns = _makeCodeSearch();
	}
	
	if (UserStudentID()) {
		$current_student_link = '
				<a href="'
					.'Modules.php'
					.'?modname=' . $_REQUEST['modname']
					.'&modfunc=student'
					.'&month_date=' . $_REQUEST['month_date']
					.'&day_date=' . $_REQUEST['day_date']
					.'&year_date=' . $_REQUEST['year_date']
					.'&student_id=' . UserStudentID()
				.'">'._('Current Student')
				.'</a>
			</td>
			<td>';
	}

	DrawHeader(PrepareDate($date, '_date', false, array('submit' => true)),
			'<table>
				<tr>
					<td>'
						.$current_student_link.button('add','',"# onclick='javascript:addHTML(\"".str_replace('"','\"',_makeCodeSearch())."\",\"code_pulldowns\"); return false;'").'
					</td>
					<td>
						<div id="code_pulldowns">'
							.$code_pulldowns.'
						</div>
					</td>
				</tr>
			</table>
			');

	$categories_RET = DBGet(DBQuery(
			"SELECT      ID
			  ,          TITLE 
			 FROM        ATTENDANCE_CODE_CATEGORIES 
			 WHERE       SYEAR = '$user_syear' 
			  AND        SCHOOL_ID = '$user_school'"
			));
			
	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['table']);
	unset($tmp_REQUEST['codes']);

	$tmp_PHP_SELF = PreparePHP_SELF($tmp_REQUEST);
	
	if (count($categories_RET)) {
		if ($_REQUEST['table'] !== '0') {
			$tabcolor = 'DFDFDF';
			$textcolor = '666666';
		}
		else {
			$tabcolor = Preferences('HIGHLIGHT');
			$textcolor = 'FFFFFF';
		}

		$header .= '
				<td width="10"></td>
				<td>'
					.DrawTab('Attendance'
							, $tmp_PHP_SELF.'&amp;table=0'
							, $tabcolor
							, $textcolor
							, '_circle'
							, array('tabcolor' => Preferences('HIGHLIGHT')
								, 'textcolor'  => 'FFFFFF')
							).'
				</td>';
				
		foreach ($categories_RET as $category) {
			if ($_REQUEST['table'] !== $category['ID']) {
				$tabcolor = 'DFDFDF';
				$textcolor = '666666';
			}
			else {
				$tabcolor = Preferences('HIGHLIGHT');
				$textcolor = 'FFFFFF';
			}

			$header .= '
					<td width="10"></td>
					<td>'
						.DrawTab($category['TITLE']
								, $tmp_PHP_SELF.'&amp;table='.$category['ID']
								, $tabcolor
								, $textcolor
								, '_circle'
								, array('tabcolor' => Preferences('HIGHLIGHT')
									, 'textcolor'  => 'FFFFFF')
								).'
					</td>';
		}
		echo TabsHeader($header);
	}

	$_REQUEST['search_modfunc'] = 'list';
	Search('student_id',$extra);
	
	echo '	<br />
			<CENTER>
				'.SubmitButton(_('Update')).'
			</CENTER>
		</form>';
}

function _makePhone($value, $column)
{	global $THIS_RET
	,      $contacts_RET
	;

	if (count($contacts_RET[$THIS_RET['STUDENT_ID']])) {
		foreach ($contacts_RET[$THIS_RET['STUDENT_ID']] as $person) {
			if ($person[1]['FIRST_NAME'] || $person[1]['LAST_NAME']) {
				$tipmessage .= '<b>'
								. $person[1]['STUDENT_RELATION'] . ': '
								. $person[1]['FIRST_NAME'] . ' '
								. $person[1]['LAST_NAME']
							.  '</b>
							<br />';
			}
			
			$tipmessage .= '<table>';
			
			if ($person[1]['PHONE']) {
				$tipmessage .= '
						<tr>
							<td align="'.ALIGN_RIGHT.'">
								<font color="gray" size="1" face="Verdana,Arial,Helvetica">
									'._('Home Phone').'
								</font> 
							</td>
							<td>
								<font size="1" face="Verdana,Arial,Helvetica">
									'.$person[1]['PHONE'].'
								</font>
							</td>
						</tr>';
			}
			
			foreach ($person as $info) {
				if ($info['TITLE'] || $info['VALUE']) {
					$tipmessage .= '
							<tr>
								<td align="'.ALIGN_RIGHT.'">
									<font color="gray" size="1" face="Verdana,Arial,Helvetica">
										'.$info['TITLE'].'
									</font>
								</td>
								<td>
									<font size="1" face="Verdana,Arial,Helvetica">
										'.$info['VALUE'].'
									</font>
								</td>
							</tr>';
				}
			}
			$tipmessage .= '</table>';
		}
	}
	else {
		$tipmessage = _('This student has no contact information.');
	}
	return button('phone'
				, ''
				, '# onMouseOver=\'stm(["'._('Contact Information').'","'
						. str_replace("'", "&rsquo;"
						, str_replace('"', "\\\""
						, str_replace("\n", ""
						, str_replace("\t", ""
						, $tipmessage))))
						. '"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",,,,]);\' onMouseOut=\'htm()\''
				);
}

function _makePhoto($value, $column)
{	global $THIS_RET
	,      $StudentPicturesPath
	,      $contacts_RET
	;

	if ($StudentPicturesPath 
	&& ($file = @fopen($StudentPicturesPath . ($syear = UserSyear()) . '/' . $THIS_RET['STUDENT_ID'] . '.JPG','r') 
		|| $file = @fopen($StudentPicturesPath . ($syear = (UserSyear() - 1)) . '/' . $THIS_RET['STUDENT_ID'] . '.JPG','r'))
	){
		return '<div onMouseOver=\'stm(["'.str_replace("'",'&rsquo;',$THIS_RET['FULL_NAME']).'","<IMG SRC='.str_replace('\\','\\\\',$StudentPicturesPath).$syear.'/'.$THIS_RET['STUDENT_ID'].'.JPG>"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",,,,]);\' onMouseOut=\'htm()\'>
				<img src="assets/camera.gif" 
					border="0" 
					width="20" 
					alt="photo"
				/>				
				</div>';
		}
	else {
		return '<img src="assets/no-camera.gif" 
					border="0" 
					width="20"
                    alt="no photo"					
					title="Sorry, no photo available"
				/>
				';
	}
}
	
function _makeCodePulldown($value,$title)
{	global $THIS_RET
	,      $codes_RET
	,      $current_RET
	,      $current_schedule_RET
	,      $date
	,      $day
	,      $user_school
	,      $user_syear
	,      $mp_list
	;

	if (!is_array($current_schedule_RET[$THIS_RET['STUDENT_ID']])) {
		$current_schedule_RET[$THIS_RET['STUDENT_ID']] = DBGet(DBQuery("
				SELECT       cp.PERIOD_ID
				 ,           cp.COURSE_PERIOD_ID 
				FROM         SCHEDULE s
				 JOIN        COURSE_PERIODS cp 
				  ON         cp.COURSE_PERIOD_ID = s.COURSE_PERIOD_ID 
				WHERE        s.STUDENT_ID = '$THIS_RET[STUDENT_ID]' 
				 AND         s.SYEAR = '$user_syear' 
				 AND         s.SCHOOL_ID='$user_school' 
				 AND         cp.DOES_ATTENDANCE = 'Y' 
				 AND         cp.DAYS LIKE '%$day%' 
				 AND         s.MARKING_PERIOD_ID IN ($mp_list) 
				 AND         '$date' >= s.START_DATE 
				 AND         ('$date' <= s.END_DATE OR s.END_DATE IS NULL)
				ORDER BY     s.START_DATE ASC
				"), array(), array('PERIOD_ID'));
				
		if (!$current_schedule_RET[$THIS_RET['STUDENT_ID']]) {
			// shouldnt this be "boom" - BL
			$current_schedule_RET[$THIS_RET['STUDENT_ID']] = array();
		}
	}
	
	if ($THIS_RET['COURSE']) {
//		$period = $THIS_RET['COURSE_PERIOD_ID'];
		$period_id = $THIS_RET['PERIOD_ID'];
		
		foreach ($codes_RET as $code) {
			$options[$code['ID']] = $code['TITLE'];
		}
	}
	else {	// i'm sory, did someone initialize a variable named $title while I wasnt watching?  -BL
		$period_id = substr($title, 7);
//		$period = $current_schedule_RET[$THIS_RET['STUDENT_ID']][$period_id][1]['COURSE_PERIOD_ID'];
		
		foreach ($codes_RET as $code) {
			$options[$code['ID']] = $code['SHORT_NAME'];
		}
	}
	
	$val = $current_RET[$THIS_RET['STUDENT_ID']][$period_id][1]['ATTENDANCE_CODE'];

	if ($current_schedule_RET[$THIS_RET['STUDENT_ID']][$period_id]) {
		return SelectInput($val
				, 'attendance['.$THIS_RET['STUDENT_ID'].']['.$period_id.'][ATTENDANCE_CODE]'
				, ''
				, $options
				, ''
				, ''
				, 'force'
				);
	}
	else {
		return false;
	}	
}

function _makeCode($value,$title)
{	global $THIS_RET
	,      $codes_RET
	,      $current_RET
	;

	foreach ($codes_RET as $code) {
		if ($current_RET[$THIS_RET['STUDENT_ID']][$THIS_RET['PERIOD_ID']][1]['ATTENDANCE_TEACHER_CODE'] == $code['ID']) {
			return $code['TITLE'];
		}
	}
}

function _makeReasonInput($value,$title)
{	global $THIS_RET
	,      $codes_RET
	,      $current_RET
	;

	$val = $current_RET[$THIS_RET['STUDENT_ID']][$THIS_RET['PERIOD_ID']][1]['ATTENDANCE_REASON'];

	return TextInput($val
			, 'attendance['.$THIS_RET['STUDENT_ID'].']['.$THIS_RET['PERIOD_ID'].'][ATTENDANCE_REASON]'
			, ''
			, ''
			, 'force'
			);
}

function _makeCodeSearch($value='')
{	global $codes_RET
	,      $code_search_selected
	;

	$return = '<SELECT name="codes[]"><OPTION value="">'._('All').'</OPTION>'
			.'<OPTION value="A"'.(($value=='A')?' SELECTED':'').'>NP</OPTION>';
			
	if (count($codes_RET)) {
		foreach ($codes_RET as $code) {
			if ($value == $code['ID']) {
				$return .= '<OPTION value="'.$code['ID'].'" SELECTED>'
						.$code['SHORT_NAME']
						.'</OPTION>';
			}
			else {
				$return .= '<OPTION value="'.$code['ID'].'">'
						.$code['SHORT_NAME']
						.'</OPTION>';
			}
		}
	}

	$return .= '</SELECT>';
	
	return $return;
}

function _makeStateValue($value,$name)
{	global $THIS_RET
	,      $date
	;
	
	$value = DBGet(DBQuery("
			SELECT       STATE_VALUE
			 ,           COMMENT 
			FROM         ATTENDANCE_DAY 
			WHERE        STUDENT_ID = '$THIS_RET[STUDENT_ID]' 
			 AND         SCHOOL_DATE = '$date'
			"));
			
	if ($name == 'STATE_VALUE') {
		$value  = $value[1]['STATE_VALUE'];
		
		if ($value == '0.0') {  //this smells like a function
			return 'None';
		}
		elseif ($value == '.5') {
			return 'Half-Day';
		}
		else {
			return 'Full-Day';
		}
	}
	else {
		return TextInput($value[1]['COMMENT']
				, 'attendance_day['.$THIS_RET['STUDENT_ID'].'][COMMENT]'
				, ''
				, ''
				, 'force'
				);
	}
}

?>